using Core.SimpleTemp.Application.YH;
using Core.SimpleTemp.Common;
using Core.SimpleTemp.Common.AutoMapperExtend;
using Core.SimpleTemp.Common.BaseLibrary;
using Core.SimpleTemp.Common.PagingQuery;
using Core.SimpleTemp.Entitys;
using Core.SimpleTemp.Repositories;
using Core.Toolkit.Common;
using Core.Toolkit.Core;
using Core.Toolkit.Core.Api;
using Core.Toolkit.Core.Application;
using Core.Toolkit.Core.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Core.SimpleTemp.Application
{
    /// <summary>
    /// 场所环境
    /// </summary>
    [AutoDi()]
    public class YH_EnvironmentService : YH_BaseService<YH_EnvironmentDto, YH_Environment, YH_EnvironmentRepository>
    {
        readonly ExcelHelp _excelHelp;
        readonly TempDirDiHelp _TempDirHelp;
        readonly IDataDicHelp _dataDicHelp;
        readonly IHttpContextAccessor _accessor;
        readonly UserIdentity _userIdentity;
        readonly YHService _yHService;
        public YH_EnvironmentService(
            YH_EnvironmentRepository repository, ExcelHelp excelHelp,
            TempDirDiHelp tempDirHelp, IDataDicHelp dataDicHelp,
            IHttpContextAccessor accessor, YHService yHService) : base(repository)
        {
            _excelHelp = excelHelp;
            _TempDirHelp = tempDirHelp;
            _dataDicHelp = dataDicHelp;
            _accessor = accessor;
            _userIdentity = accessor.HttpContext.User.GetUserIdentity();
            _userIdentity = accessor?.HttpContext?.User?.GetUserIdentity();
            _yHService = yHService;
        }



        public override LoadPageOffsetModel<YH_Environment, YH_EnvironmentDto>
            GetLoadPageOffsetMode(PagingModel<YH_EnvironmentDto>
                pagingQueryModel)
        {
            var dtoModel = pagingQueryModel.Model;
            var AreaIds = dtoModel.AreaIds;
            var loadPageOffsetModel = this.GetLoadPageOffsetModel(pagingQueryModel);
            var baseQuery = _repository.QueryBase().AsNoTracking();
            var filterList = this.CreateQRList()
             .Add("AreaID", "=") //区域ID
             .Add("PlaceEnvironment", "=") //场所环境
             .Add("EnergySource", "=") //能量源
             .Add("RiskLevel", "=") //隐患等级ID
             .Add("CheckStandard", "=") //检查标准
             .Add("RiskOfViolation", "=") //违反标准的风险
             .Add("CreateFactory", "=") //隶属工厂
             .Add("CreateDept", "=") //
             .Add("UpdateDept", "=");//
                                     //工厂处理
            if (_userIdentity.Headoffice)
                filterList.Add("CreateFactory", "="); //总部从查询条件取工厂id
            else
                filterList.Add("CreateFactory", "=", _userIdentity.Factory);
            var filterExpre = filterList.BuildeQR(dtoModel.ToEntity<YH_Environment>());
            //区域处理
            if (AreaIds != null && AreaIds.Any())
                filterExpre = filterExpre != null ? filterExpre.And(a => AreaIds.Contains(a.AreaID.Value)) : a => AreaIds.Contains(a.AreaID.Value);
            //filterExpre = filterExpre.And(a => AreaIds.Contains(a.AreaID.Value));
            loadPageOffsetModel.QueryWhere = filterExpre;
            loadPageOffsetModel.BasqQuery = baseQuery;
            loadPageOffsetModel.Order = orderModel => orderModel.CreateTime;
            loadPageOffsetModel.Selector = model => new YH_Environment()
            {
                Id = model.Id,
                AreaID = model.AreaID,//区域ID
                PlaceEnvironment = model.PlaceEnvironment,//场所环境
                EnergySource = model.EnergySource,//能量源
                RiskLevel = model.RiskLevel,//隐患等级ID
                CheckStandard = model.CheckStandard,//检查标准
                RiskOfViolation = model.RiskOfViolation,//违反标准的风险
                CreateFactory = model.CreateFactory,//隶属工厂
                CreateDept = model.CreateDept,//
                UpdateDept = model.UpdateDept,//
            };
            return loadPageOffsetModel;
        }


        public async Task<IPageModel<YH_EnvironmentDto>> GetList(PagingModel<YH_EnvironmentDto>
            pagingQueryModel)
        {
            var loadPageOffsetModel = GetLoadPageOffsetMode(pagingQueryModel);
            return await base.LoadPageOffsetAsync(loadPageOffsetModel);
        }


        public async Task<string>
            Export(PagingModel<YH_EnvironmentDto>
                pagingQueryModel)
        {
            const string FILE_NAME_PREFIX = "排查标准_场所环境";
            Guid userFactory = (Guid)_userIdentity.Factory;
            var sysAreas = await _yHService.GetAreaByFactoryAsync();
            var loadPageOffsetModel = GetLoadPageOffsetMode(pagingQueryModel);
            var DataList = await this.ExportDataAsync(loadPageOffsetModel);
            var excelData = DataList.Select(model => new
            {

                model.PlaceEnvironment,
                PlaceEnvironment_title = "场所环境",
                model.EnergySource,
                EnergySource_title = "能量源",
                model.CheckStandard,
                CheckStandard_title = "检查标准",
                model.RiskOfViolation,
                RiskOfViolation_title = "违反标准的风险",
                model.RiskLevelText,
                RiskLevelText_title = "隐患等级",
                Area = sysAreas.Where(a => a.Id == model.AreaID).FirstOrDefault()?.Name,
                Area_title = "区域",
            }).ToList();

            var fileName = FILE_NAME_PREFIX + TempDirHelp.GetTimeStampFielName(".xlsx");
            return _excelHelp.Create(excelData, fileName);
        }


        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="file"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<List<string>> ImportAsync(IFormFile file, string data)
        {
            //当前用户工厂ID
            Guid userFactory = (Guid)_userIdentity.Factory;
            var extension = System.IO.Path.GetExtension(file.FileName);
            var filePath = _TempDirHelp.GetFilePath(extension);
            await Filehelp.WriteFileAsync(file.OpenReadStream(), filePath);

            var dataList = new List<YH_Environment>();
            var errMsgList = new List<string>();
            var sysAreas = await _yHService.GetAreaByFactoryAsync();
            IWorkbook workbook = new XSSFWorkbook(filePath);
            try
            {
                var sheet = workbook.GetSheetAt(0);
                int rowCount = sheet.LastRowNum;
                //验证模板是否正确
                var first = sheet.GetRow(0);
                if (first.GetCell(0)?.ToString() != "场所环境" ||
                    first.GetCell(1)?.ToString() != "能量源" ||
                    first.GetCell(2)?.ToString() != "检查标准" ||
                    first.GetCell(3)?.ToString() != "违反标准的风险" ||
                    first.GetCell(4)?.ToString() != "隐患等级"
                    //||
                    //first.GetCell(5)?.ToString() != "区域"
                    )
                {
                    errMsgList.Add($"请确认模板是否正确!");
                }
                for (int i = 1; i <= rowCount; i++)
                {
                    var row = sheet.GetRow(i);
                    var entity = new YH_Environment();
                    //entity.TypeID = Guid.Parse(data);

                    if (string.IsNullOrWhiteSpace(row.GetCell(0)?.ToString()))
                        errMsgList.Add($"第{i}行，【场所环境】列 不能为空！");
                    else
                        entity.PlaceEnvironment = row.GetCell(0)?.ToString();


                    entity.EnergySource = row.GetCell(1)?.ToString();


                    entity.CheckStandard = row.GetCell(2)?.ToString();


                    entity.RiskOfViolation = row.GetCell(3)?.ToString();
                    if (!string.IsNullOrWhiteSpace(row.GetCell(4)?.ToString()))
                    {
                        var riskLevelId = this.GetRiskLevelId(row.GetCell(4).ToString());

                        if (riskLevelId == Guid.Empty)
                            errMsgList.Add($"第{i}行，【隐患等级】列 数据异常");
                        else
                            entity.RiskLevel = riskLevelId;
                    }
                    entity.CreateFactory = userFactory;
                    //区域
                    if (!string.IsNullOrWhiteSpace(row.GetCell(5)?.ToString()))
                    {
                        var factoryName = row.GetCell(5)?.ToString();
                        var sysarea = _yHService.FindAreaOfAreaListAsync(sysAreas, factoryName);
                        if (sysarea == null)
                            errMsgList.Add($"第{i}行，【区域】列 区域名是否正确！");
                        entity.AreaID = sysarea.Id;
                    }
                    dataList.Add(entity);
                }
            }
            catch (Exception ex)
            {
                //errMsgList.Add($"导入异常:" + ex.Message);
            }
            finally
            {
                workbook.Close();
            }
            if (errMsgList.Any())
                return errMsgList;
            await _repository.Set.AddRangeAsync(dataList);
            await _repository.SaveAsync();
            System.IO.File.Delete(filePath);
            return errMsgList;
        }

        private Guid GetRiskLevelId(string RiskLeve)
        {
            var riskLevelId = Guid.Empty;
            var list = _dataDicHelp.GeDataDicValueByCategory(YH_GradeService.DATA_DIC_KEY);
            list.ForEach(a =>
            {
                if (a.Value == RiskLeve)
                    riskLevelId = Guid.Parse(a.Key);
            });
            return riskLevelId;
        }

    }

}
